<!DOCTYPE html>
<html>
<head>
    <title>SheetJS Live Grid Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="icon" type="image/png" href="assets/img/logo.png" />
    <link rel="stylesheet" href="assets/css/sheetjs.css">
</head>
<body>
    <script src="assets/vendor/alertify.js"></script>
    <script src="assets/vendor/jquery.min.js"></script>
    <script src="assets/vendor/jquery.handsontable.full.js"></script>

    <link rel="stylesheet" media="screen" href="assets/vendor/jquery.handsontable.full.css">
    <link rel="stylesheet" media="screen" href="assets/vendor/samples.css">
    <link rel="stylesheet" media="screen" href="assets/vendor/alertify.css">

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>




    <div id="body">



        <div id="left">
            <div id="logo">
                <a href="http://poker.520code.cc/basic/web/index.php?r=user-poker%2Findex"><img src="assets/img/logo.png" class="logo" alt="SheetJS Logo" width=128px height=128px /></a>
            </div>
            <div id="drop">拖放到这里</div>
            <h3>  选择sheet:</h3>
            <div id="buttons" style="display:none;"></div>
        </div>
        <div id="right">
            <div id="header" style="height:250px;">
                <pre id="out"></pre>
                <h2>批量录入数据</h2>
                <a class="btn btn-primary" href="http://poker.520code.cc/basic/web/index.php?r=user-poker%2Findex">返回牌局列表</a>
                <h3>
                    拖动excel表格到拖动框里面上传数据<br/>

                </h3>
              <!--   <div style="">
                 <button type="button" class="btn btn-lg btn-success" onclick="save_date();">提交数据到系统</button>
                </div> -->



                <!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  提交数据到系统
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">提示</h4>
      </div>
      <div class="modal-body">
        确认提交数据录入到系统吗？
        <div class="progress" style="display: none;">
              <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%">
                <span class="sr-only">100% Complete (success)</span>
              </div>
            </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" onclick="save_date();">确认保存</button>
      </div>
    </div>
  </div>
</div>







            </div>
            <div id="hot" style="overflow: scroll" class="handsontable"></div>





            <div>
                <p>录入说明</p>

                <p>excel的表格格式，如果格式没有按照下面的会导致录入失败</p>
                <div class="widget-content">
                         <table id="campaignlistt" class="table table-bordered table-striped">
                             <thead>
                                 <tr>
                                    <th>时间</th>
                                     <th>桌号</th>
                                     <th>ID</th>
                                     <th>战绩</th>
                                     <th>客人结算</th>
                                     <th>反水</th>
                                     <th>最终结算</th>
                                     <th>俱乐部</th>
                                 </tr>
                             </thead>
                             <tbody id="table_div">
                                <tr class="gradeA">
                                <td class="center">2017-05-10</td>
                                <td class="center">5</td>
                                <td class="center">文森特2017</td>
                                <td class="center">-334,432</td>
                                <td class="center">-334,432</td>
                                <td class="center">8,288</td>
                                <td class="center">-326,144</td>
                                <td class="center">斗战胜佛</td>
                                </tr>
                                 <tr class="gradeA">
                                <td class="center">2017-05-10</td>
                                <td class="center">5</td>
                                <td class="center">文森特2017</td>
                                <td class="center">-334,432</td>
                                <td class="center">-334,432</td>
                                <td class="center">8,288</td>
                                <td class="center">-326,144</td>
                                <td class="center">斗战胜佛</td>
                                </tr>
                            </tbody>
                        </table>

            </div>
            <div>
                <a class="btn btn-primary" href="http://poker.520code.cc/basic/sheetjs/temp.xlsx">下载excel模板文件</a>
            </div>

           <!--  <div id="footnote">
                <h3>
                    This particular parser assumes that <b>the first row of the table is a header.</b><br/>
                    For parsing a more general file, check the Interactive Demos
                </h3><br/>
                <h3>The entire process occurs within your browser <br />
                    <b>NO SPREADSHEET DATA IS SENT TO ANY SERVER (parsing and rendering done in your browser)</b></br>
                <h3>This is a work in progress.  Every bit helps.  Please email <a href="mailto:dev@sheetjs.com">dev@sheetjs.com</a> with your feedback.
                <h3>Follow us on Twitter <a href="https://twitter.com/SheetJS">@SheetJS</a></h3>
            </div> -->
        </div>

        <script src="assets/js/shim.js"></script>
        <script src="assets/js/xlsx.full.min.js"></script>
        <script src="assets/js/dropsheet.js"></script>
        <!-- <script src="assets/js/main.js"></script> -->

        <script src="assets/vendor/spin.js"></script>


        <script type="text/javascript">

        var va = 10;

        function timepick()
        {
            va +=10;
            if(va > 95){
                va = 95;
            }
            $(".progress-bar").attr("style","width: "+va+"%;");


            t=setTimeout("timepick()",100)
    

        }


        function save_date(){


            try{

                 var hotInstance = $("#hot").handsontable('getInstance');//获取数据
                var data = hotInstance.getData();

                // console.log(data);

                var info = [];
                for (var i = 1; i < data.length; i++) {
                    info.push(data[i]);
                };

                var str = JSON.stringify(info);
                $(".progress").show();
                va = 10;
                timepick();
                $.ajax({
                  type: "POST",
                  url: "/basic/web/index.php?r=mobie/ajax-save-data",
                  data: { data: str}
                  }).done(function( ua_msg ) {
                    // $(".progress").hide();
                    if(ua_msg != ""){
                        var info = JSON.parse(ua_msg);
                        if(info.code == 0){
                            window.location.href = "http://poker.520code.cc/basic/web/index.php?r=user-poker%2Findex";
                        }
                    }
                    
                  });

            }catch(e){

                alert("没有获取到数据,请先提交数据");


            }

           




        }

            /** drop target **/
            var _target = document.getElementById('drop');

            /** Spinner **/
            var spinner;

            var _workstart = function() { spinner = new Spinner().spin(_target); }
            var _workend = function() { spinner.stop(); }

            /** Alerts **/
            var _badfile = function() {
              alertify.alert('This file does not appear to be a valid Excel file.  If we made a mistake, please send this file to <a href="mailto:dev@sheetjs.com?subject=I+broke+your+stuff">dev@sheetjs.com</a> so we can take a look.', function(){});
          };

          var _pending = function() {
              alertify.alert('Please wait until the current file is processed.', function(){});
          };

          var _large = function(len, cb) {
              alertify.confirm("This file is " + len + " bytes and may take a few moments.  Your browser may lock up during this process.  Shall we play?", cb);
          };

          var _failed = function(e) {
              console.log(e, e.stack);
              alertify.alert('We unfortunately dropped the ball here.  We noticed some issues with the grid recently, so please test the file using the direct parsers for <a href="/js-xls/">XLS</a> and <a href="/js-xlsx/">XLSX</a> files.  If there are issues with the direct parsers, please send this file to <a href="mailto:dev@sheetjs.com?subject=I+broke+your+stuff">dev@sheetjs.com</a> so we can make things right.', function(){});
          };

          /** Handsontable magic **/
          var boldRenderer = function (instance, td, row, col, prop, value, cellProperties) {
              Handsontable.TextCell.renderer.apply(this, arguments);
              $(td).css({'font-weight': 'bold'});
          };

          var $container, $parent, $window, availableWidth, availableHeight;
          var calculateSize = function () {
              var offset = $container.offset();
              availableWidth = Math.max($window.width() - 250,600);
              availableHeight = Math.max($window.height() - 250, 400);
          };

          $(document).ready(function() {
              $container = $("#hot"); $parent = $container.parent();
              $window = $(window);
              $window.on('resize', calculateSize);
          });

          /* make the buttons for the sheets */
          var make_buttons = function(sheetnames, cb) {
              var $buttons = $('#buttons');
              $buttons.html("");
              sheetnames.forEach(function(s,idx) {
                var button= $('<button/>').attr({ type:'button', name:'btn' +idx, text:s });
                button.append('<h3>' + s + '</h3>');
                button.click(function() { cb(idx); });
                $buttons.append(button);
                $buttons.append('<br/>');
            });
          };
          var json_data = [];
          var _onsheet = function(json, cols, sheetnames, select_sheet_cb) {
              $('#footnote').hide();
              json_data = json;


              var user_name_s = [];
              var club_name_s = [];
              for (var i = 0; i < json_data.length; i++) {
                  var ob = json_data[i];
                  var club =  ob["俱乐部"];
                  var poker_name = ob["ID"];
// http://poker.520code.cc/basic/web/index.php?r=mobie/ajax-id-by-club-name&name=%E9%BD%90%E5%A4%A9%E5%A4%A7%E5%9C%A3
// http://poker.520code.cc/basic/web/index.php?r=mobie/ajax-id-by-name&name=xiaochun
//http://poker.520code.cc/basic/web/index.php?r=mobie/add-club&name=xiaochun34
//http://poker.520code.cc/basic/web/index.php?r=mobie/add-user&name=xiaochun34
user_name_s.push(poker_name);
club_name_s.push(club);
}


// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) {  
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function get_names_res(info,clubs,ua_info){
   $.ajax({
      type: "POST",
      url: "/basic/web/index.php?r=mobie/ajax-clubs",
      data: { name: clubs.join('||')}
  }).done(function( msg ) {
      // console.log(msg);



          for(var i = 0 ; i < json_data.length;i++){ 

            var data = json_data[i];
            if(i == -1){
                data["用户id"] = "用户id";
                data["俱乐部id"] = "俱乐部id";
            }else{
                data["用户id"] = JSON.parse(info)[data["ID"]];
                data["俱乐部id"] = JSON.parse(msg)[data["俱乐部"]];

                var json_ua_info =  JSON.parse(ua_info);

                var ui_id =  data["用户id"];
                if(json_ua_info.hasOwnProperty("ui_"+ui_id)){
                    data["代理id"] = json_ua_info["ui_"+ui_id];
                    data["代理名字"] = json_ua_info["ua_"+data["代理id"]];
                }else{
                    data["代理id"] = '无';
                    data["代理名字"] = '无';
                }

                if(!data.hasOwnProperty("时间")){
                    data["时间"] = new Date().Format("yyyy-MM-dd");   
                }

            }
        }


        json = json_data;


        make_buttons(sheetnames, select_sheet_cb);
        calculateSize();

        /* add header row for table */
        if(!json) json = [];
        json.unshift(function(head){
            head.push("用户id");
            head.push("俱乐部id");
            head.push("代理id");
            head.push("代理名字");
            if($.inArray("时间", head)==-1){
                head.push("时间");
            }

            var o = {}; for(i=0;i!=head.length;++i) o[head[i]] = head[i]; 
            return o;}(cols));
        calculateSize();
        /* showtime! */
        $("#hot").handsontable({
            data: json,
            startRows: 5,
            startCols: 3,
            fixedRowsTop: 1,
            stretchH: 'all',
            rowHeaders: true,
            columns: cols.map(function(x) { return {data:x}; }),
            colHeaders: cols.map(function(x,i) { return XLS.utils.encode_col(i); }),
            cells: function (r,c,p) {
              if(r === 0) this.renderer = boldRenderer;
          },
          width: function () { return availableWidth; },
          height: function () { return availableHeight; },
          stretchH: 'all'
      });

        /** Drop it like it's hot **/
        DropSheet({
          drop: _target,
          on: {
            workstart: _workstart,
            workend: _workend,
            sheet: _onsheet,
            foo: 'bar'
        },
        errors: {
            badfile: _badfile,
            pending: _pending,
            failed: _failed,
            large: _large,
            foo: 'bar'
        }
    })










    });
}

$.ajax({
  type: "POST",
  url: "/basic/web/index.php?r=mobie/ajax-names",
  data: { name: user_name_s.join('||')}
}).done(function( msg ) {
  // console.log(msg);

  var ids_info =  JSON.parse(msg);
  var ids_ = Object.keys(ids_info);
  var ids = [];
  for (var i = 0; i < ids_.length; i++) {
      var key = ids_[i];
      if(key != "cnt"){
        ids.push(ids_info[key]);

      }
  }
      $.ajax({
          type: "POST",
          url: "/basic/web/index.php?r=mobie/ajax-agents",
          data: { ids: ids.join('||')}
      }).done(function( ua_msg ) {

        get_names_res(msg,club_name_s,ua_msg); 
      });

  
});




//  make_buttons(sheetnames, select_sheet_cb);
//  calculateSize();
//
//  /* add header row for table */
//  if(!json) json = [];
//  json.unshift(function(head){var o = {}; for(i=0;i!=head.length;++i) o[head[i]] = head[i]; return o;}(cols));
//  calculateSize();
//  /* showtime! */
//  $("#hot").handsontable({
//    data: json,
//    startRows: 5,
//    startCols: 3,
//    fixedRowsTop: 1,
//    stretchH: 'all',
//    rowHeaders: true,
//    columns: cols.map(function(x) { return {data:x}; }),
//    colHeaders: cols.map(function(x,i) { return XLS.utils.encode_col(i); }),
//    cells: function (r,c,p) {
//      if(r === 0) this.renderer = boldRenderer;
//    },
//    width: function () { return availableWidth; },
//    height: function () { return availableHeight; },
//    stretchH: 'all'
//  });
};
//
///** Drop it like it's hot **/
DropSheet({
  drop: _target,
  on: {
    workstart: _workstart,
    workend: _workend,
    sheet: _onsheet,
    foo: 'bar'
},
errors: {
    badfile: _badfile,
    pending: _pending,
    failed: _failed,
    large: _large,
    foo: 'bar'
}
})
//

 // var hotInstance = $("#hot").handsontable('getInstance');获取数据
 //hotInstance.getData();



</script>



<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36810333-1']);
  _gaq.push(['_setDomainName', 'sheetjs.com']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>













</body>
</html>
